/*  header-comment
/*  file   : /Users/arida/react-hrm-h5/src/components/Select/index
/*  author : arida
/*  date   : 2017-6-4 18:27:27
/*  last   : 2017-7-2 15:1:38
*/
import React, { Component } from "react";
import { List } from "@ali/ding-ui";
import PropTypes from "prop-types";
import autobind from "autobind-decorator";

/**
 * @class  Select组件
 */
class Select extends Component {
  constructor(props) {
    super(props);
  }
  static defaultProps = {
    options: [],

    onChange: () => null
  };
  static propTypes = {
    value: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.bool,
      PropTypes.number
    ]),
    options: PropTypes.array.isRequired,
    placeholder: PropTypes.string,
    onChange: PropTypes.func,
    children: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.array,
      PropTypes.string
    ])
  };

  getLabel(options, value) {
    // fix fuck Android JSAPI BUG
    const match = options.filter(
      option => String(option.value) === String(value)
    );
    return match[0] && match[0].label;
  }
  @autobind
  handleOnChange(value) {
    dd.biz.util.chosen({
      source: this.props.options.map(option => ({
        key: option.label,
        value: option.value
      })),
      selectedKey: this.getLabel(this.props.options, value), // 默认选中的key
      onSuccess: result => {
        this.props.onChange(result.value);
      },
      onFail: function(err) {}
    });
  }

  render() {
    const { value, options, placeholder } = this.props;

    return (
      <List.Item
        onClick={this.handleOnChange.bind(null, value)}
        arrow="horizontal"
        extra={this.getLabel(options, value) || placeholder || "请选择"}
      >
        {this.props.children}
      </List.Item>
    );
  }
}

export default Select;
